import matplotlib
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np

#中文支持
matplotlib.rcParams['font.sans-serif']=['SimHei']

img = mpimg.imread('example.png')   #png图像是4通道的，最后一个通道是alpha层，示例中用不到
lum_img = (img[:,:,0]+img[:,:,1]+img[:,:,2])/3  #取rgb三色的平均值，使得通道只有1个
core1=np.array([-1,-1,1,1]).reshape(2,2)    #检测水平的核
core2=np.array([1,-1,1,-1]).reshape(2,2)    #检测竖线的核
core3=np.array([1,-1,-1,1]).reshape(2,2)    #检测斜线的核
core=[core1,core2,core3]
nplum_img=np.array(lum_img)
d=1 #步长为1
h,w=nplum_img.shape #拿到图片的形状
npresult=[np.zeros((h-1,w-1)),np.zeros((h-1,w-1)),np.zeros((h-1,w-1))]
for i in range(h-1):
    for k in range(w-1):
        v_lu=nplum_img[i,k]
        v_ru=nplum_img[i,k+1]
        v_ld=nplum_img[i+1,k]
        v_rd=nplum_img[i+1,k+1]
        window=np.array([v_lu,v_ru,v_ld,v_rd]).reshape(2,2)
        for j in range(3):
            npresult[j][i,k]=abs((window*core[j]).sum())

fig = plt.figure()
fig.add_subplot(2, 3, 2).set_title('原图片')
imgplot=plt.imshow(lum_img,cmap="gray")
fig.add_subplot(2, 3, 4).set_title('检测水平')
imgplot=plt.imshow(npresult[0],cmap="gray")
fig.add_subplot(2, 3, 5).set_title('检测竖线')
imgplot=plt.imshow(npresult[1],cmap="gray")
fig.add_subplot(2, 3, 6).set_title('检测对角')
imgplot=plt.imshow(npresult[2],cmap="gray")
fig.tight_layout()
plt.show()
